package com.service;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.Nullable;

import com.myapp.MyApp;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.RequestManager;
import com.xiaochun.hxhj.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

public class DeviceService2 extends Service {

    private Handler handlerdelay;
    private SharedPreferences sharedPreferences;

    @Override
    public void onCreate() {
        handlerdelay = new Handler();
        sharedPreferences = getSharedPreferences("userinfo", Activity.MODE_PRIVATE);
        MyLog.e("开启服务","onCreate()");

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            //Android8以上
            NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel Channel = new NotificationChannel("111","主服务",NotificationManager.IMPORTANCE_HIGH);
            Channel.enableLights(true);//设置提示灯
            Channel.setLightColor(Color.RED);//设置提示灯颜色
            Channel.setShowBadge(true);//显示logo
            Channel.setDescription("ytzn");//设置描述
            Channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); //设置锁屏可见 VISIBILITY_PUBLIC=可见
            manager.createNotificationChannel(Channel);

            Notification notification = new Notification.Builder(this)
                    .setChannelId("111")
                    .setContentTitle("中科慧学慧记")//标题
                    .setContentText("运行中...")//内容
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.icon_notifition_small_icon)//小图标一定需要设置,否则会报错(如果不设置它启动服务前台化不会报错,但是你会发现这个通知不会启动),如果是普通通知,不设置必然报错
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                    .build();
            startForeground(1,notification);//服务前台化只能使用startForeground()方法,不能使用 notificationManager.notify(1,notification); 这个只是启动通知使用的,使用这个方法你只需要等待几秒就会发现报错了
        }else{
            //Android8以下
            Notification notification = new Notification.Builder(this)
                    .setContentTitle("中科慧学慧记")//设置标题
                    .setContentText("运行中...")//设置内容
                    .setWhen(System.currentTimeMillis())//设置创建时间
                    .setSmallIcon(R.mipmap.icon_notifition_small_icon)//设置状态栏图标
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))//设置通知栏图标
                    .build();
            startForeground(1,notification);
        }



        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String device_time = MyApp.device_time;
        if ("".equals(device_time)){
            device_time = "3000";
        }
        final String devicetime = device_time;
        MyLog.e("开启服务","onStartCommand()   间隔时长"+device_time);
        handlerdelay.postDelayed(new Runnable() {
            @Override
            public void run() {
//                MyLog.e("服务执行定时任务","服务执行定时任务");
                String token = sharedPreferences.getString("token", "");
                if (!"".equals(token) && MyApp.isRequest){
                    getData();
                }
                handlerdelay.postDelayed(this, Integer.parseInt(devicetime));


            }
        },Integer.parseInt(devicetime));


        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    private void getData() {
        String token = sharedPreferences.getString("token", "");
        String url = MyApp.siteurl + "/api/user/device";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("device_id",MyApp.deviceId);
        paramsMap.put("token",token);
        RequestManager.getInstance(this).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
//                MyLog.e("服务定时请求任务", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("123")) {
                        String str = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        EventBus.getDefault().post(new InfoEventMessage("设备ID已更新退出登录",str));
//                        isRequest = false;
                        MyApp.setIsRequest(false);
                    }else{
//                        isRequest = true;
                        MyApp.setIsRequest(true);
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                }
            }
        });
    }




}